package com.truth.lock.executor.redisson;

import com.truth.lock.executor.TruthLockExecutor;
import org.redisson.api.RLock;

import java.util.concurrent.TimeUnit;

/**
 * @author truth
 */
public interface RedissonLockExecutor extends TruthLockExecutor<RLock> {

    /**
     * 执行redisson锁操作
     * @param lockInstance Redisson锁实例
     * @param expire 锁的有效期
     * @param acquireTimeout 获取锁的超时时间
     * @return 是否获取锁成功
     */
    default boolean lock(RLock lockInstance, long expire, long acquireTimeout) {
        boolean locked = false;
        try {
            if (acquireTimeout == -1 && expire == -1) {
                lockInstance.lock();
                locked = lockInstance.isLocked();
            } else if (acquireTimeout == -1) {
                lockInstance.lock(expire, TimeUnit.MILLISECONDS);
                locked = lockInstance.isLocked();
            } else if (expire != -1) {
                locked = lockInstance.tryLock(acquireTimeout, expire, TimeUnit.MILLISECONDS);
            } else {
                lockInstance.lock();
                locked = lockInstance.isLocked();
            }
        } catch (InterruptedException e) {
            return false;
        }
        return locked;
    }

}
